<template>
    <view class="content">
        <van-nav-bar :title="navBarTitle" left-arrow @click-left="onClickLeft" class="navBar">
        </van-nav-bar>
        <view class="page">
            <view class="pageTopScanArea">
                <view class="" v-if="!isShowCapturedImage">
                    <!-- mode="scanCode" @scancode="scancode" -->
                    <camera class="scan-camera" device-position="back" flash="auto" @error="cameraError"
                        frame-size="large" @initdone="initCamera" ></camera>
                </view>
                <view v-else class="captured-image-container">
                    <image class="scan-camera" :src="capturedImagePath"></image>
                    <!-- 添加遮罩层 -->
                    <view class="image-overlay"></view>
                </view>
                <!-- <view class="scan-frame"></view> -->
                <view class="playIcon" v-if="!isScanning" @click="toggleScan"> <img src="https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/playIcon.png" alt="" style="width: 120rpx;height: 120rpx;"> </view>
                <view class="toggleScan">
                    <!-- 添加控制扫码的按钮 -->
                    <van-button type="info" @click="toggleScan"> {{ isScanning ? '暂停扫码' : '重扫/继续扫码' }} </van-button>
                </view>
            </view>

            <view class="scanListWrapper">
                <view class="scanStatistic" v-if="handle=='scanOut' ">已扫码列表({{resultList.length}}) </view>
                <view class="userInfo_right deliveryMethod" v-if="handle=='scanIn' ">
                    <view class="tab-bar gray">
                        <view class="tabbar-item" v-for="(item, index) in tabBarList"
                            @click="changeTab(index, $event, item.name)"
                            :class="{ active: index === currentIndex,'left':index==0,'right':index==1 } " :key="index">
                            {{ item.name }}
                        </view>
                    </view>
                </view>
                <scroll-view class="scroll-content" scroll-y :lower-threshold="80" @scroll="scrollPage"
                    show-scrollbar="false" @scrolltolower="loadMore">
                    <view class="expressListBox">
                        <scanInAndOut :resultList="resultList" @checkbox-change="handleCheckboxChange"
                            @handlechecked="handlechecked" :check-all="checkAll" @showMoreAction="showMoreAction">
                        </scanInAndOut>
                    </view>
                    <view class="scan-result">
                        <text>扫码结果: {{ scanResult }}</text>
                    </view>
                </scroll-view>
            </view>

        </view>
        <template>
            <view class="bottom">
                <van-button type="primary" class="button" @click="handleConfirm"
                    v-if="handle=='scanOut'">全部出库</van-button>
                <van-button type="primary" class="button" @click="handleConfirm"
                    v-if="handle=='scanIn'">全部提交</van-button>
            </view>
        </template>

    </view>
</template>
<script>
import Toast from '@/wxcomponents/vant/toast/toast'
import scanInAndOut from '@/mycomponents/merchant/scanInAndOut.vue'

export default {
    components:{
        scanInAndOut,
    },
    props: {
        show: {
            type: Boolean,
            default: () => false
        },
        popupParams: {
            type: Object,
            default: () => ({})
        }
    },
    data () {
        return {
            scrolling: false, // 是否正在滚动
            navBarTitle:'快件查询',
            searchPlaceholder: 'Enter tracking number',
            searchButton: 'Search',
           
            current:0, //当前选中的tab
            status: {
                notOutbound: 'Not Outbound',
                outbound: 'Outbound'
            },
            searchValue: '',
            tabActive: 0,
            expressList: [
                { phone: '198****1000', name: '刘*而', status: 1 },
                { phone: '185****1000', name: '张桐二', status: 1 },
                { phone: '15232651000', name: '孙*俪', status: 0 },
                { phone: '18546781000', name: '刘*娥', status: 0 }
            ],
            phoneCount:4, //同名字不同手机数量
            packagesCount:2, //未出库包裹数量
            resultList:[
                {
                    waybillNumber:'1234567890124',
                    pickupCode:'2205',
                    status:'已出库',
                    address:'北京市海淀区',
                    time:'2023-10-10 10:10:10',
                    name:"张伟",
                    phone:"18546781000",
                },
                {
                    waybillNumber:'1234567890123',
                    pickupCode:'2203',
                    status:'已出库',
                    address:'北京市海淀区',
                    time:'2023-10-10 10:10:10',
                    name:"张伟",
                    phone:"18546781000",
                },
                {
                    waybillNumber:'1234567890125',
                    pickupCode:'2205',
                    status:'已出库',
                    address:'北京市海淀区',
                    time:'2023-10-10 10:10:10',
                    name:"张伟",
                    phone:"18546781000",
                },
                {
                    waybillNumber:'1234567890127',
                    pickupCode:'22036',
                    status:'已出库',
                    address:'北京市海淀区',
                    time:'2023-10-10 10:10:10',
                    name:"张伟",
                    phone:"18546781000",
                }
            ],

            checkAll: false, // 全选状态
            selectedRowKeys: [], // 已选择的数据的id
            selectedRows: [], // 已选择的数据
            checked: [],
            inactiveIcon:
                'https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/notChecked1126.png',
            activeIcon:
                'https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/goodsChecked1126.png',
            disabledIcon: 'https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/disabledIcon.png',
            isShowBlue: false,

            currentIndex: 0, // 配送方式的tab索引
            tabBarList: [
                {
                    name: '自提',
                    key: '0'
                },
                {
                    name: '送货上门',
                    key: '1'
                }
            ],
            params:{},
            handle:undefined,
            scanResult: '',
            scanIntervalId: null,
            scanErrorCount: 0, // 扫码失败次数
            maxErrorCount: 3, // 最大失败次数
            scanPause: false, // 是否暂停扫描
            isScanning: false, // 新增状态，记录扫码状态
            capturedImagePath: '', // 用于存储拍照后的图片路径
            isShowCapturedImage: false, // 用于判断是否显示拍照留存的图片
            cameraContext: null
        }
    },

    computed: {
    },

    watch:{
        resultList: {
            immediate: true,
            handler(val) {
                console.log(val)
                var i = 0
                this.resultList.forEach(item => {
                    if (item.isChecked === true) {
                        i++
                    }
                    this.checkAll = i === this.resultList.length
                })
            },
            deep: true
        },
        checked: {
            handler (val) {
                console.log(val, 'newName')
            }
        },
        selectedRowKeys: {
            handler (val) {
                console.log(val, 'selectedRowKeys')
                if (val.length > 0) {
                    this.isShowBlue = true // 标记为正常的按钮  深蓝色
                } else {
                    this.isShowBlue = false // 标记为正常的按钮  浅蓝色
                }
            }
        },
        selectedRows: {
            handler (val) {
                console.log(val, 'selectedRows')
            }
        },

    },
    onLoad (data) {
        // 取到路由携带的参数
        if (data && data.params) {
            this.params = JSON.parse(decodeURIComponent(data.params || '{}'))
            console.log('params', this.params)
            this.handle = this.params.handle

        }
      
    },
    // 页面卸载前清除定时器
    onUnload() {
        this.pauseScan(); // 页面卸载时确保清除定时器
    },
    onReady () {
        this.resultList.forEach(ele => {
            this.$set(ele, 'isChecked', false)
        });

     },

    methods: {
        // 滑动
        scrollPage(e) {
            console.log(e.detail.scrollTop, this.scrolling)
            if (e.detail.scrollTop > 25 && !this.scrolling) {
                this.scrolling = true
            } else if ((e.detail.scrollTop <= 25 && this.scrolling) || (e.detail.scrollTop <= 25 && !this.scrolling)) {
                this.scrolling = false
            }
        },
        // 返回键
        onClickLeft() {
            uni.navigateBack()
        },

        // 触底
        loadMore() {
            // 这里可以添加加载更多的逻辑
            console.log('触底了');
        },
        // 初始化摄像头
        initCamera() {
            // this.startContinuousScan();
            this.cameraContext = uni.createCameraContext()
        },
        scancode(e) {
            console.log('扫码结果:', e.detail);
            this.scanResult = e.detail.result
            this.resultList.forEach(item => {
                if (item.waybillNumber === this.scanResult) {
                    item.isChecked = true
                }
            })
        },
        // 手动触发扫码
        startScan() {
            if (this.scanErrorCount >= this.maxErrorCount) {
                uni.showToast({ title: '扫码多次失败，请检查摄像头', icon: 'none' });
                return;
            }

            this.isScanning = true
            // 先拍照
            this.cameraContext.takePhoto({
                quality: 'high',
                success: (res) => {
                    console.log('拍照成功', res);
                    this.capturedImagePath = res.tempImagePath
                    // 保存图片到相册
                    uni.saveImageToPhotosAlbum({
                        filePath: this.capturedImagePath,
                        success: () => {
                            console.log('图片保存成功');
                        },
                        fail: (err) => {
                            console.error('图片保存失败', err);
                        }
                    });
                    // 拍照成功后执行扫码
                    uni.scanCode({
                        onlyFromCamera: true,
                        success: (res) => {
                            console.log('扫码结果:', res);
                            this.handleScanResult(res.result);
                            this.scanErrorCount = 0; // 扫码成功，重置失败次数

                        },
                        fail: (err) => {
                            console.error('扫码失败:', err);
                            this.scanErrorCount++; // 扫码失败，增加失败次数
                            if (this.scanErrorCount >= this.maxErrorCount) {
                                uni.showToast({ title: '扫码多次失败，请检查摄像头', icon: 'none' });
                            }
                        },
                        complete: () => {
                            this.isShowCapturedImage = true
                            this.isScanning = false
                        }
                    });
                },
                fail: (err) => {
                    console.error('拍照失败', err);
                    this.isScanning = false
                    this.isShowCapturedImage = false
                }
            })
        },
        startContinuousScan() {
            // 如果已经在扫描中，则不再重复启动
            if (this.scanIntervalId) return;

            let isScanningInner = false;
            const scanInterval =3000; // 每2秒扫描一次

            const performScan = () => {
                if (isScanningInner || !this.isScanning || this.scanPause) return;
                isScanningInner = true;

                uni.scanCode({
                    onlyFromCamera: true,
                    success: (res) => {
                        console.log('Scan result:', res);
                        this.handleScanResult(res.result);
                        this.scanErrorCount = 0;
                        this.scanPause = true; // 扫码成功后暂停扫描
                        setTimeout(() => {
                            this.scanPause = false; // 2秒后恢复扫描
                        }, 2000);
                    },
                    fail: (err) => {
                        console.error('Scan failed:', err);
                        this.scanErrorCount++;
                        if (this.scanErrorCount >= this.maxErrorCount) {
                            uni.showToast({ title: '扫码多次失败，请检查摄像头', icon: 'none' });
                            this.pauseScan(); // 达到最大错误次数后暂停扫描
                        }
                    },
                    complete: () => {
                        isScanningInner = false;
                    }
                });
            };
            performScan(); // 立即执行首次扫描
            this.scanIntervalId = setInterval(performScan, scanInterval);
        },
        // 处理扫码结果
        handleScanResult(result) {
            this.scanResult = result;
            const newResult = {
                waybillNumber: result,
                pickupCode: '',
                status: '已扫码',
                address: '',
                time: new Date().toISOString(),
                name: '',
                phone: ''
            };
            this.resultList.push(newResult);
            // 显示更详细的提示信息
            uni.showToast({
                title: `扫码成功，结果为：${result}`,
                icon: 'success'
            });
            console.log('处理扫描结果:', result);
            this.isShowCapturedImage = true
            this.isScanning = false
        },

        // // 处理扫码结果
        // handleScanResult(result) {
        //     this.scanResult = result;
        //     const newResult = {
        //         waybillNumber: result,
        //         pickupCode: '',
        //         status: '已扫码',
        //         address: '',
        //         time: new Date().toISOString(),
        //         name: '',
        //         phone: ''
        //     };
        //     this.resultList.push(newResult);
        //     // 显示更详细的提示信息
        //     uni.showToast({
        //         title: `扫码成功，结果为：${result}`,
        //         icon: 'success'
        //     });
        //     console.log('处理扫描结果:', result);

        //     // 拍照并保存图片
        //     // this.takePhoto();
        //      // 拍照并保存图片逻辑
        //      uni.chooseImage({
        //         count: 1,
        //         sizeType: ['original', 'compressed'],
        //         sourceType: ['camera'],
        //         success: (res) => {
        //             console.log(res,'res')
        //             debugger
        //             const tempFilePaths = res.tempFilePaths;
        //             this.capturedImagePath = tempFilePaths[0];
        //             this.isShowCapturedImage = true
        //             // 保存图片到相册
        //             uni.saveImageToPhotosAlbum({
        //                 filePath: this.capturedImagePath,
        //                 success: () => {
        //                     console.log('图片保存成功');
        //                 },
        //                 fail: (err) => {
        //                     console.error('图片保存失败', err);
        //                     this.isScanning = false

        //                 }
        //             });
        //             this.isScanning = false;

        //         },
        //         fail: (err) => {
        //             console.error('拍照失败', err);
        //             this.isScanning = false;

        //         }
        //     });
        //     // 暂停扫描
        //     this.pauseScan();
        //     // 更新扫描状态
        //     this.isScanning = false;
        //     // 显示拍照留存的图片
        //     this.isShowCapturedImage = true;
        //     // 自动暂停扫码
        //     // this.isScanning = false;
        //     //  // 拍照并保存图片
        //     // this.takePhoto();

        // },
       

        // 摄像头出错处理
        cameraError(e) {
            console.error('摄像头初始化失败:', e.detail);
            uni.showToast({ title: '请开启摄像头权限', icon: 'none' });
        },
        // 切换扫码状态
        toggleScan() {
            this.isScanning = !this.isScanning; 
            console.log(this.isScanning,'isScanning')
            if (this.isScanning) {
                this.isShowCapturedImage = false; // 切换到继续扫码时，隐藏拍照留存的图片
                this.rescan(); // 如果是继续扫码，则重新开始扫描
            } else {
                this.pauseScan(); // 如果是暂停扫码，则停止扫描
                this.isShowCapturedImage = true; // 暂停扫码时显示图片
            }
        },

        // 暂停扫码
        pauseScan() {
            if (this.scanIntervalId) {
                clearInterval(this.scanIntervalId);
                this.scanIntervalId = null;
            }
        },

        // 继续/重新扫码
        rescan() {
            this.cameraContext = uni.createCameraContext()
            this.startScan()
            // this.scanErrorCount = 0; // 重置错误计数
            // this.startContinuousScan(); // 重新开始持续扫码
            // uni.scanCode({
            //     onlyFromCamera: true,
            //     success: (res) => {
            //         this.handleScanResult(res.result);
            //     },
            //     fail: (err) => {
            //         console.error('Scan failed:', err);
            //         uni.showToast({ title: '扫码失败，请重试', icon: 'none' });
            //         this.isScanning = false;
            //     }
            // });
        },
        // rescan() {
        //     // 这里添加重扫/继续扫的逻辑
        //     // 可以简单理解为重新触发扫码操作
        //     if (this.scanErrorCount >= this.maxErrorCount) {
        //         this.scanErrorCount = 0; // 若之前扫码失败次数达到上限，重置失败次数
        //     }
        //     this.scanPause = false; // 确保可以进行扫码
        //     this.startContinuousScan(); // 重新开始持续扫码
        // },
      


        changeTab(index, e, itemName) {
            this.currentIndex = index
            console.log(index, itemName)
            // this.$emit('sliderSelect', index, itemName)
        },


        // 多选单选全选
        handleCheckboxChange({item, checked}) {
            console.log(item, 'i', checked, 'c')
            const index = this.selectedRowKeys.indexOf(item.waybillNumber)
            console.log(index, 'indes')
            if (item.isChecked === true) {
                if (index === -1) {
                    this.selectedRowKeys.push(item.waybillNumber)
                    this.selectedRows.push(item)
                }
                // this.selectedRowKeys.push(item.waybillNumber)
                // this.selectedRows.push(item)
            } else {
                this.selectedRowKeys.splice(index, 1)
                this.selectedRows.splice(index, 1)
            }
            console.log(this.selectedRowKeys, 'selectedRowKeys')
            this.checkAll = this.selectedRowKeys.length === this.resultList.length
            this.resultList.forEach(ele => {
                if (ele.waybillNumber === item.waybillNumber) {
                    ele.isChecked = checked
                }
            })
        },
        // 标记  选择框  文字
        handlechecked (item, checked) {
            console.log(item, checked, '单选----')
            this.checkAll = this.checked.length === this.resultList.length
            const index = this.selectedRowKeys.indexOf(item.waybillNumber)

            if (checked === true) {
                this.selectedRowKeys.push(item.waybillNumber)
                this.selectedRows.push(item)
            } else {
                console.log(index, 'indesR')
                this.selectedRowKeys.splice(index, 1)
                this.selectedRows.slice(index, 1)
            }
            this.resultList.forEach(ele => {
                if (ele.waybillNumber === item.waybillNumber) {
                    ele.isChecked = checked
                }
            })

        },
        // 全选后面的文字
        onChangeItem (type, item) {
            console.log(type, 'type', 'onChange')
            if (type === '多选') {
                this.checkAll = !this.checkAll
                console.log(this.checked)
                this.handleSelectAll(this.checkAll, !this.select)

            } else {
                // if (this.select && (item.onOffShelvesStatus === false || item.productStock <= 0)) {
                //     return false;
                // }
                // item.status = !item.status;
                // this.handleCheckLogic(item, item.status);
            }
        },
        handleSelectAll(checked, isManageMode) {
            const targetList = this.resultList
            const allCheckedIds = targetList.map(item => item.waybillNumber)
            targetList.forEach(item => { item.isChecked = checked })

            if (checked) {
                this.checked = allCheckedIds;
                this.selectedRows = JSON.parse(JSON.stringify(targetList));
            } else {
                this.checked = [];
                this.checkAll = false;
                this.selectedRows = [];
            }
            this.selectedRowKeys = this.checked;
        },

        // 处理全选
        handleCheckAll(val) {
            console.log(val, '全选按钮')
            const checkAll = val.detail
            const targetList = this.resultList
            const allCheckedIds = targetList.map(item => item.waybillNumber)
            targetList.forEach(item => { item.isChecked = checkAll })
            if (checkAll) {
                this.selectedRows = JSON.parse(JSON.stringify(targetList));
                this.checked = allCheckedIds
            } else {
                this.selectedRows = []
                this.checked = []
            }
            this.selectedRowKeys = this.checked
            console.log(this.resultList, 'resultList')
        },

        // 一键出库
        allTakeOut(){
            if(this.selectedRowKeys.length==0){
                return false
            }
            console.log(this.selectedRowKeys,'selectedRowKeys')
            console.log(this.selectedRows,'selectedRows')
        },
    },

}
</script>
<style lang="scss" scoped>
::v-deep .navBar .van-icon {
    color: #242629 !important;
}
.content {
    background-color: #ffffff;
    display: flex;
    flex-direction: column;
    height: 100vh;
    overflow: hidden;
    box-sizing: border-box;
    padding-bottom: calc(0rpx + env(safe-area-inset-bottom));
}

.page{
    display: flex;
    flex-direction: column;
    height: 100vh;
    overflow: hidden;
    box-sizing: border-box;
}
.scroll-content {
    flex: 1;
    height: 1px;
}
.pageTopScanArea{
    height: 750rpx;
    width: 100%;
    position: relative;
    // overflow: hidden;
    background: #f5f5f5;
}
/* 图片容器设置为相对定位 */
.captured-image-container {
    position: relative;
    width: 100%;
    height: 480rpx;
}

/* 遮罩层样式 */
.image-overlay {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.4); /* 半透明黑色遮罩 */
    z-index: 10; /* 确保遮罩层在图片上方 */
}

.scan-camera {
    width: 100%;
    height: 480rpx;
    background: rgb(0, 0, 0, 0.4);
    position: relative;
}
.scan-camera image {
    width: 100%;
    height: 100%;
    object-fit: cover;
}
.scan-frame {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 400rpx;
    height: 400rpx;
    border: 6rpx solid #00ff00;
    box-shadow: 0 0 20rpx rgba(0, 255, 0, 0.5);
}
// 图片中间的暂停按钮
.playIcon{
    position: absolute;
    top: 35%;
    left: 45%;
    z-index: 100;
    width: 80rpx;
    height: 80rpx;
}
// 暂停继续扫码按钮
.toggleScan{
    position: absolute;
    right: 10%;
    bottom: 10%;
    z-index: 100;
}
// 重扫 继续扫按钮
.rescanButton {
    position: absolute;
    top: 50%;
    right: 50rpx; /* 距离右侧50rpx，可调整 */
    transform: translateY(-50%);
}
.scanListWrapper{
    display: flex;
    flex-direction: column;
    height: 100vh;
    overflow: hidden;
    box-sizing: border-box;
    background: #fff;
    margin-bottom: 142rpx;
}

// 搜索结果的数据统计
.scanStatistic{
    padding-top: 48rpx;
    padding-bottom: 40rpx;
    background: #fff;
    font-weight: bolder;
    font-size: 28rpx;
    text-align: left;
    color: #333;
    letter-spacing: 0;
    line-height: 64rpx;
    padding-left: 48rpx;
    span{
        color: #FF6203;
    }
}
.tab-bar{
    margin: 48rpx 48rpx 0 48rpx;
    // padding:0px 2px;
    height: 80rpx;
    // background: #e43232;
    border: 1px solid #ff6203;
    border-radius: 50rpx;
    display: flex;
    align-items: center;
    justify-content: center;
}
//自提  同城配送
.gray{
  // padding:2px;
  height: 80rpx;
  border-radius: 50rpx;
  .tabbar-item {
    flex: 1;
    z-index: 1;
    height: 80rpx;
    line-height: 80rpx;
    text-align: center;
    font-size: 32rpx;
    color: #FF6203;

    &.active {
      background: #FF6203;
      color: #ffffff;
    }

  }
  .left{
    border-radius: 50rpx 0 0 50rpx;
  }
  .right{
    border-radius: 0 50rpx 50rpx 0;
  }
}

.scan-result{
    padding-bottom: 142rpx;
}
.btn-area{
    padding-top:32rpx;
    padding-left:48rpx ;
    padding-right: 48rpx;
    padding-bottom: calc(32rpx + env(safe-area-inset-bottom));
    // height: calc(144rpx + env(safe-area-inset-bottom));
    width: calc(100% - 96rpx);
    display: flex;
    z-index: 100;
    justify-content: space-between;
}

.checked-img {
    height: 16px;
    width: 16px;
}
// 页面底部的按钮
::v-deep .bottom .van-button--primary {
  width: 100% !important;
  height: 86rpx;
  border-radius: 50rpx;
  background: #ff6203;
  font-size: 28rpx;
}

::v-deep .van-button--warning {
    background-color: #FF6203;
}

// 动作面版
.van-action-sheet__header {
    font-size: var(--action-sheet-header-font-size,16px);
    font-weight: var(--font-weight-bold,500);
    line-height: var(--action-sheet-header-height,48px);
    text-align: left;
    padding: 0 48rpx !important;
}
::v-deep .toggleScan .van-button--info {
    width: 224rpx !important;
    height: 80rpx;
    border-radius: 8rpx;
    background: rgb(255, 255, 255, 0.4);
    border: none;
    font-weight: bolder;
    font-size: 28rpx;
    color: #fff;
}

</style>